package com.ebt.m.customer.view;

import android.media.MediaPlayer;
import android.os.CountDownTimer;
import android.os.Environment;
import android.util.Log;

import com.czt.mp3recorder.MP3Recorder;
import com.ebt.m.utils.DateUtils;

import java.io.File;
import java.io.IOException;
import java.util.Date;

import static com.ebt.m.utils.ConfigData.DATA_PATH;

public class RecorderWrapper{

    public static final String RECORDER_DIR
            = DATA_PATH + File.separator + "recorder";

    public static final String RECORDER_FILE_SUFFIX = ".mp3";//.3gp

    public static final long RECORDER_MAX_DURATION = 60 * 1000;//最长60s
    public static final long RECORDER_COUNT_DOWN_SECOND = 5;//最后五秒钟开始倒计时

    private MediaPlayer mPlayer = null;
    private MP3Recorder mRecorder;
    private String mRecorderAbsoluteFileName = null;
    private String mPlayerAbsoluteFileName = null;

//    private Timer mRecordTimer;

    public enum RecorderState {
        Idle, Recording, Pause
    }
    public enum PlayerState{
        Idle, Playing, Pause
    }

    private RecorderState mRecorderState = RecorderState.Idle;
    private PlayerState mPlayerState = PlayerState.Idle;

    private static RecorderWrapper instance;
    private RecorderWrapper(){
    }

    public static RecorderWrapper getInstance(){
        if(instance == null){
            synchronized (RecorderWrapper.class){
                if(instance == null){
                    instance = new RecorderWrapper();
                }
            }
        }
        mkDirForRecorderDir(RECORDER_DIR);
        return instance;
    }

    private static void mkDirForRecorderDir(String dir){
        File file = new File(dir);
        if(!file.exists()){
            file.mkdirs();
        }
    }

    public String getRecorderAbsoluteFileName(){
    	return mRecorderAbsoluteFileName;
    }

    public String getPlayerAbsoluteFileName(){
        return mPlayerAbsoluteFileName;
    }

    public static String generateSimpleFileName(){
    	Date date = new Date();
    	return "recorder_" + DateUtils.dateTime2String(date, DateUtils.YYYY_MM_DD_HH_MM_SS_S_file_name) + RECORDER_FILE_SUFFIX;
    }
    
	public void startRecord(String simpleFileName) throws IOException {
		mRecorderAbsoluteFileName = RECORDER_DIR + simpleFileName;
        File f = new File(mRecorderAbsoluteFileName);
        if(!f.exists()) {
            try {
                f.createNewFile();
            }catch (Exception e){
                e.printStackTrace();
            }
        }

        mRecorder = new MP3Recorder(new File(mRecorderAbsoluteFileName));

        try {
            mRecorder.start();
            mRecorderState = RecorderState.Recording;

            /*if(mRecordTimer != null){
                mRecordTimer.cancel();
                mRecordTimer = null;
            }*/
            if(mc != null){
                mc.cancel();
                mc = null;
            }
            /*mRecordTimer = new Timer();
            mRecordTimer.schedule(new TimerTask() {
                @Override
                public void run() {
                    stopRecord();
                }
            }, RECORDER_MAX_DURATION);*/

            mc = new MyCount(RECORDER_MAX_DURATION, 1000);
            mc.start();

        } catch (IOException e) {
            Log.e("record", "start() failed e is " + e.getMessage());
            e.printStackTrace();
        }
    }

    private MyCount mc;

    class MyCount extends CountDownTimer {

        public MyCount(long millisInFuture, long countDownInterval) {
            super(millisInFuture, countDownInterval);
            System.out.println("你好");
        }
        @Override
        public void onTick(long millisUntilFinished) {
            if(mCountDownListener != null){
                mCountDownListener.onTick(millisUntilFinished);
            }
        }
        @Override
        public void onFinish() {
            if(mCountDownListener != null){
                mCountDownListener.onFinish();
            }
        }
    }

    public interface CountDownListener{
        void onTick(long remainMillisSecond);
        void onFinish();
    }

    private CountDownListener mCountDownListener;

    public void setCountDownListener(CountDownListener listener){
        mCountDownListener = listener;
    }

	/*public void stopRecord(){
        try {
            mRecorder.stop();
        }catch(Exception e){
            //java.lang.RuntimeException: stop failed.
            e.printStackTrace();
        }
        try{
            mRecorder.release();
        }catch (Exception e){
            e.printStackTrace();
        }finally {
            mRecorderState = RecorderState.Idle;
            mRecorder = null;
        }
    }*/

    public void stopRecord(){
        try {
            if(mRecorder.isRecording()) {
                mRecorder.stop();
            }
        }catch(Exception e){
            //java.lang.RuntimeException: stop failed.
            e.printStackTrace();
        }finally {
            mRecorderState = RecorderState.Idle;
            mRecorder = null;
            /*if(mRecordTimer != null){
                mRecordTimer.cancel();
                mRecordTimer = null;
            }*/
            if(mc != null){
                mc.cancel();
                mc = null;
            }
        }
    }

    public void deleteRecordFile(String absoluteFileName){
    	File file = new File(absoluteFileName);
    	if(file.exists()){
    		file.delete();
    	}
    }
    
    public void playRecordFile(String fileName){
    	mPlayer = new MediaPlayer();
        try{
            mPlayer.setDataSource(fileName);
            mPlayer.prepare();
            mPlayer.start();
            mPlayerState = PlayerState.Playing;
        }catch(IOException e){
            Log.e("record","playRecordFile exception " + e.getMessage());
        }
    }

    public void stopPlayRecordFile(){
        if(mPlayer != null) {
            mPlayer.pause();
            mPlayer.release();
            mPlayerState = PlayerState.Idle;
            mPlayer = null;
        }
    }

    public void pausePlayRecordFile(){
        if(mPlayer != null) {
            mPlayer.pause();
            mPlayerState = PlayerState.Pause;
        }
    }

    public PlayerState getPlayerState(){
        return mPlayerState;
    }

    public RecorderState getRecorderState(){
        return mRecorderState;
    }

    public boolean isPlaying(){
        if(mPlayer != null) {
            return mPlayer.isPlaying();
        }else{
            return false;
        }
    }

    public void releasePlayer(){
        if(mPlayer != null) {
            mPlayer.reset();
            mPlayer.release();
        }
    }

    public void setPlayerOnCompletionListener(MediaPlayer.OnCompletionListener onCompletionListener){
        if(mPlayer != null) {
            mPlayer.setOnCompletionListener(onCompletionListener);
        }
    }

    private void updateMicStatus() {
        /*if (mMediaRecorder != null) {
            double ratio = (double)mMediaRecorder.getMaxAmplitude() /BASE;
            double db = 0;// 分贝
            if (ratio > 1)
                db = 20 * Math.log10(ratio);
            Log.d(TAG,"分贝值："+db);
            mHandler.postDelayed(mUpdateMicStatusTimer, SPACE);
        }*/
    }

    /*    public RecorderWrapper(Context context, String recorderDir){
    	mRecorderDir = recorderDir;
    	File file = new File(mRecorderDir);
        if(!file.exists()){
        	file.mkdirs();
        }
    }*/
}